package com.cjq.auth.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * 短信工具类
 */
@Log4j2
@Configuration
@ConfigurationProperties(prefix = "dy")
@Data
public class TelSmsUtils {

    /**
     * 阿里云主账号AccessKey，accessKeySecret拥有所有API的访问权限
     */
    private String accessKeyId;

    private String accessKeySecret;

    /**
     * 短信访问域名
     */
    private String endpoint;

    /**
     * 短信签名
     */
    private String signName;

    /**
     * 模板编号
     */
    private String templateCode;

//    @Bean
    public Client initClient() {
        log.info("初始化短信服务开始");
        long startTime = System.currentTimeMillis();
        Client client = null;
        try {
            Config config = new Config()
                    // 您的AccessKey ID
                    .setAccessKeyId(accessKeyId)
                    // 您的AccessKey Secret
                    .setAccessKeySecret(accessKeySecret);
            // 访问的域名
            config.endpoint = endpoint;
            client = new Client(config);
            log.info("初始化短信成功：{}", signName);
        } catch (Exception e) {
            log.error("初始化短信客户端失败，错误信息：{}",  e.getMessage());
        }
        log.info("初始化短信服务结束：耗时：{}MS", (System.currentTimeMillis() - startTime));
        return client;
    }

    /**
     * 发送单条短信
     *
     * @param tel
     * @param sendDataMap
     *
     */
    public SendSmsResponseBody sendSms(String tel, Map<String, String> sendDataMap) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(tel)
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setTemplateParam(JSONObject.toJSONString(sendDataMap));
        SendSmsResponse sendSmsResponse = null;
        try {
            log.info("发送短信验证码：消息内容是：【{}】", JSONObject.toJSONString(sendDataMap));
            sendSmsResponse = initClient().sendSms(sendSmsRequest);
        } catch (Exception e) {
            log.error("短信发送异常，手机号：【{}】，短信内容：【{}】，异常信息：【{}】", tel, sendDataMap, e);
        }
        return sendSmsResponse.getBody();
    }

}
